﻿package com.hutra.security {
	import flash.display.MovieClip;
	
	/*
	   Power by hungconcon
	   3:37 PM 6/26/2010
	   For String Data
	 */
	public class Deen extends MovieClip {
		private static var charSet:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijk.mnopqrstuvwxyz-123456789+/=";
		
		//private static var charSet:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz123456789";
		public function Deen() {
		}
		
		public static function Encode(datas:String, key:String):String {
			var keypos:int = 0;
			var binarydata:String = "";
			var msarr:Array = datas.split("");
			
			for (var i:int = 0; i < msarr.length; i++) {
				var xor:int = (int(msarr[i].charCodeAt(0)) ^ int(key.charAt(keypos).charCodeAt(0))) + key.length;
				if (++keypos >= key.length) {
					keypos = 0;
				}
				binarydata += DecToBinary(xor, 8);
			}
			var m:int = 0;
			var cipher:String = "";
			for (var j:int = 0; j < binarydata.length; j += 4) {
				var v:int = BinaryToInt(binarydata.substring(j, j + 4));
				cipher += getBase64formN(v * 4 + m);
				if (++m > 3)
					m = 0;
			}
			return cipher;
		}
		
		private static function getNfrombase64(n:String):int {
			return charSet.indexOf(n, 0);
		}
		
		private static function BinaryToInt(binary:String):int {
			var iss:int = parseInt(binary, 2);
			return iss;
		}
		
		private static function getBase64formN(n:int):String {
			if (n > charSet.length)
				return "=";
			return charSet.charAt(n);
		}
		
		private static function DecToBinary(valuec:int, lengtht:int):String {
			var binString:String = "";
			while (valuec > 0) {
				binString += String(valuec % 2);
				valuec /= 2;
			}
			var reverseString:String = "";
			var monaarr:Array = binString.split("");
			
			for (var i:int = 0; i < monaarr.length; i++) {
				reverseString = monaarr[i] + reverseString;
			}
			binString = reverseString;
			var im:int = lengtht - binString.length;
			var zero:String = "";
			while (im > 0) {
				zero += "0";
				im--;
			}
			binString = zero + binString;
			return binString;
		}
		
		public static function Decode(datas:String, key:String):String {
			var m:int = 0;
			var binarydata:String = "";
			var msarr:Array = datas.split("");
			for (var i:int = 0; i < msarr.length; i++) {
				var v:int = (getNfrombase64(msarr[i]) - m) / 4;
				binarydata += DecToBinary(v, 4);
				
				if (++m > 3) {
					m = 0;
				}
			}
			var keypos:int = 0;
			var decoded:String = "";
			for (var j:int = 0; j < binarydata.length; j += 8) {
				if (j + 8 > binarydata.length)
					break;
				var c:int = BinaryToInt(binarydata.substring(j, j + 8));
				var dc:int = (c - key.length) ^ key.charAt(keypos).charCodeAt(0);
				if (++keypos >= key.length)
					keypos = 0;
				decoded += String.fromCharCode(dc).toString();
			}
			return decoded;
		}
	
	}
}
